let canSend = false;
$(function () {
    var curtime = (new Date()).getTime() / 1000;
    $("#curtime").html(timestampToTime(curtime));

    $('#footer').on('keyup', 'input', function () {
        if ($(this).val().length > 0) {
            $(this).next().css('background', '#114F8E').prop('disabled', true);
            canSend = true;
        } else {
            $(this).next().css('background', '#ddd').prop('disabled', false);
            canSend = false;
        }
    })
    $('#footer .send').click(send)
    $("#footer .my-input").keydown(function (e) {
        if (e.keyCode == 13) {
            return send();
        }
    });
})

function reply(headSrc, str) {
    var html = "<div class='reply'><div class='msg'><img src=" + headSrc + " /><span class='name'>AI机器人</span><p><i class='msg_input'></i>" + str + "</p></div></div>";
    return upView(html);
}

function ask(headSrc, str) {
    var html = "<div class='ask'><div class='msg'><img src=" + headSrc + " />" + "<p><i class='msg_input'></i>" + str + "</p></div></div>";
    return upView(html);
}

function wait() {
    var html = "<div class='wait'>AI机器人思考中，请您耐心等待</div>";
    return upView(html);
}

function error(str) {
    var html = "<div class='wait'>" + str + "</div>";
    return upView(html);
}

function upView(html) {
    let message = $('#message');
    message.append(html);
    return $('html,body').animate({
        scrollTop: message.outerHeight() - window.innerHeight
    }, 200);
}

function send(msg) {
    if (canSend) {
        let input = $("#footer .my-input");
        // 提交问题
        var prompt = input.val();
        ask("./images/touxiangm.png", prompt);


        wait();
        input.val('');
        $.ajax({
            type: "get",
            url: "http://localhost:8080/api/chat/send",
            data: {
                "prompt": prompt
            },
            dataType: "json",
            // async: false,
            success: function (response) {
                if (response.code == 200) {
                    var data = JSON.parse(response.data);
                    reply("images/touxiang.png", data.choices[0].text)
                } else {
                    // console.log('response :>> ', response.msg);
                    error(response.msg);
                }
            }
        });

    }
}



function timestampToTime(timestamp) {
    var date = new Date(timestamp * 1000); //时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '/';
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '/';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y + M + D + h + m + s;
}